package com.jiyun.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.entity.Book;
import com.jiyun.entity.ReadList;
import com.jiyun.service.IBookService;
import com.jiyun.service.IReadListService;
import com.jiyun.vo.BookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  控制层
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-05-16
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    IBookService bookService;

    /**
     * 添加接口
     */
    @RequestMapping("/add")
    public void addBook(@RequestBody Book book){
        bookService.save(book);
    }

    /**
     * 修改接口
     */
    @RequestMapping("/update")
    public void updateBook(@RequestBody Book book){
        bookService.updateById(book);
    }

    /**
     * 单个删除接口
     */
    @RequestMapping("/deleteOne")
    public void deleteOne(@RequestParam Integer id){
        bookService.removeById(id);
    }

    /**
     * 批量删除接口
     * 前台ajax参数ids传入示例：1,2,3  (英文逗号分隔的字符串)
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(@RequestParam List<Integer> ids){
        bookService.removeByIds(ids);
    }

    /**
     * 根据id查询实体接口
     */
    @RequestMapping("/findById")
    public Book findById(@RequestParam Integer id){
        return bookService.getById(id);
    }

    /**
     * 查询所有接口
     */
    @RequestMapping("/findAll")
    public List<Book> findAll(){
        return bookService.list();
    }

    /**
     * 分页查询接口
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     */
    @RequestMapping("/findPage")
    public Page<BookVo> findPage(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestBody Book book){

        return bookService.findPage(page,pageSize,book);
    }

    @RequestMapping("readBook")
    public void readBook(Integer bid,Integer uid){
        /**
         * 设置图书状态为：借阅中
         * 借阅次数+1
         * 添加借阅记录
         */

        Book book = bookService.getById(bid);
        book.setState("借阅中");
        book.setNums(book.getNums()+1);

        bookService.updateById(book);


        ReadList readList = new ReadList();
        readList.setUid(uid);
        readList.setBid(bid);
        readList.setReadTime(new Date());


        readListService.save(readList);



    }

    @Autowired
    IReadListService readListService;

}
